﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
using SS4U.Library;
using umbraco;
using umbraco.cms.businesslogic.index;
using umbraco.presentation.dashboard;

namespace SS4U.UiSearch.AutoComplete
{
    public partial class Search : umbraco.BasePages.UmbracoEnsuredPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (helper.Request("q").Trim() != "" && getUser() != null)
            {
                var query = helper.Request("q").Trim();

                var searcher = new Searcher();
                var results = searcher.Search(query, null, "Umbraco Backend Search");
                
                var items = new List<SearchItem>();
                items.AddRange((from x in results
                                select
                                    new SearchItem
                                        {
                                            Author = "",
                                            ChangeDate = DateTime.Now,
                                            Description = x.Text,
                                            Icon = "",
                                            NodeId = x.Id,
                                            ObjectType = Guid.Empty,
                                            Tags = null,
                                            Title = x.Text
                                        }).Take(20));
                    
                var rh = new ResultHelper(items);
                var js = new JavaScriptSerializer();
                Response.Write(js.Serialize(rh));
            }
        }
    }
}
